﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MYSMRM.Model;
using MYSMRM.Manager.Interface;
using MYSMRM.Common;

namespace MYSMRM.Web.QS
{
    public partial class QuestionDetail : System.Web.UI.Page
    {
        private bool _bNew = false;
        private int _iTopicID=-1;
        private int _iQuestionID = -1;
        private QSQuestion _question;
        private QSTopic _topic;
        private DataTable _dtOption;

        public IQSTopicManager TopicManager { get; set; }
        public IQSQuestionManager QuestionManager { get; set; }
        //public IQSOptionManager OptionManager { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["I_ID"] == null)
                {
                    _bNew = true;
                }
                else
                {
                    _iQuestionID = Convert.ToInt32(Request.QueryString["I_ID"]);
                }
                if (Request.QueryString["TopicID"] != null)
                {
                    _iTopicID=Convert.ToInt32(Request.QueryString["TopicID"]);
                }

                InitData();
                FillFields();
                ViewState["TopicID"]=_iTopicID;
                ViewState["QuestionID"] = _iQuestionID;
                ViewState["dtOption"] = _dtOption;
            }
            else
            {
                _iTopicID = Convert.ToInt32(ViewState["TopicID"]);
                _iQuestionID = Convert.ToInt32(ViewState["QuestionID"]);
                _dtOption = ViewState["dtOption"] as DataTable;
            }
        }
        protected void lbtn_Add_Click(object sender, EventArgs e)
        {
            _question = new QSQuestion();
            _question.ID = _iQuestionID;
            _question.TopicID = _iTopicID;
            _question.Question = txt_Question.Text;

            _question.Sequence = Convert.ToInt32(txt_Sequence.Text);
            _question.MultiSelect = cb_MultiSelect.Checked;

            _question.LastUpdater = "";
            _question.LastUpdateDate = DateTime.Now;

            _question.Creator = "";
            _question.CreateDate = DateTime.Now;


            _question.OptionList = new List<QSOption>(); ;
            _question.AddList(DataTable2Object.ConvertToList<QSOption>(_dtOption));
            // save to database
            try
            {
                QuestionManager.Save(_question);
            }
            catch (Exception)
            {
                // TODO: record this exception with log4net
            }
        }

        protected void lbtn_Save_Click(object sender, EventArgs e)
        {
            _question = QuestionManager.Get(_iQuestionID);

            if (_question != null)
            {
                _question.ID = _iQuestionID;
                _question.TopicID = _iTopicID;
                _question.Question = txt_Question.Text;

                _question.Sequence = Convert.ToInt32(txt_Sequence.Text);
                _question.MultiSelect = cb_MultiSelect.Checked;

                _question.LastUpdater = "";
                _question.LastUpdateDate = DateTime.Now;
                _question.OptionList.Clear();
                _question.AddList(DataTable2Object.ConvertToList<QSOption>(_dtOption));

                // update to database
                try
                {
                    QuestionManager.Update(_question);
                }
                catch (Exception)
                {
                    // TODO: record this exception with log4net
                }
            }
        }

        protected void lbtn_Cancel_Click(object sender, EventArgs e)
        {
            this.Clear();
            Response.Redirect("..//QS//TopicDetail.aspx");
        }
        /// <summary>
        /// Clear all temp data for this page
        /// </summary>
        private void Clear()
        {
            // TODO: Clear all temp data for this page
        }
        protected void lbtn_AddOption_Click(object sender, EventArgs e)
        {
           // Response.Redirect("..//QS//QuestionDetail.aspx?TopicID=" + _iTopicID.ToString());
            if (_iQuestionID > 0)
            {
                if (txt_Option.Text.Trim() != "")
                {
                    // InitOptionTable();
                    //Response.Redirect("..//QS//OptionDetail.aspx?TopidID=" + _iTopicID.ToString());
                    DataRow dr = _dtOption.NewRow();
                    dr["I_ID"] = GetLargestOptionID() + 1;
                    dr["I_QUESTION_ID"] = _iQuestionID;
                    dr["S_OPTION"] = txt_Option.Text;
                    string t = this.ddlAllQuestions.SelectedValue;
                    dr["I_NEXTQUESTION"] = this.ddlAllQuestions.SelectedValue;
                    dr["B_DELETED"] = false;
                    dr["S_LAST_UPDATER"] = "";
                    dr["D_LAST_UPDATE_DATE"] = DateTime.Now;
                    _dtOption.Rows.Add(dr);

                    ViewState["dtOption"] = _dtOption;

                    BindOption();
                }
            }
        }
        #region Option Events
        

        protected void gv_Options_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            _dtOption.Rows.RemoveAt(e.RowIndex);
            _dtOption.AcceptChanges();
            ViewState["dtOption"] = _dtOption;
            BindOption();
        }

        protected void gv_Options_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gv_Options.EditIndex = e.NewEditIndex;
            BindOption();
        }

        protected void gv_Options_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gv_Options.EditIndex = -1;
            BindOption();
        }

        protected void gv_Options_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int ID = Convert.ToInt32(gv_Options.DataKeys[e.RowIndex].Value);
            foreach (DataRow dr in _dtOption.Rows)
            {
                if (Convert.ToInt32(dr["I_ID"]) == ID)
                {
                    dr["S_OPTION"] = Server.HtmlDecode(((TextBox)gv_Options.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString());
                    dr["S_LAST_UPDATER"] = "";
                    dr["D_LAST_UPDATE_DATE"] = DateTime.Now;
                    _dtOption.AcceptChanges();
                    ViewState["dtOption"] = _dtOption;
                    gv_Options.EditIndex = -1;
                    break;
                }
            }

            BindOption();
        }

        protected void gv_Options_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                    ((LinkButton)e.Row.Cells[5].Controls[0]).Attributes["onclick"] = "if(!confirm('你真的要删除" + e.Row.Cells[3].Text + "这条记录么?'))return false;";
                }
            }
        }
        #endregion
        private void BindOption()
        {
            gv_Options.DataSource = _dtOption;
            gv_Options.DataKeyNames = new string[] { "I_ID" };
            gv_Options.DataBind();
        }
        private int GetLargestOptionID()
        {
            int iResult = -1;
            for (int i = 0; i < _dtOption.Rows.Count; i++)
            {
                if (Convert.ToInt32(_dtOption.Rows[i]["I_ID"]) > iResult)
                {
                    iResult = Convert.ToInt32(_dtOption.Rows[i]["I_ID"]);
                }
            }

            return iResult;
        }
        private void InitData()
        {
            if (_iTopicID >= 0)
            {
                _topic = TopicManager.Load(_iTopicID);
            }
            // TODO: Initial data for this page
            if (_iQuestionID >= 0)
            {
                _question = QuestionManager.Load(_iQuestionID);

                _dtOption = DataTable2Object.ConvertToDataTableFromList(_question.OptionList);
            }
            else
            {
                InitOptionTable();
            }
            // TODO: initial options for topic
            //InitTestData();
        }
        private void FillFields()
        {
            if (Request.QueryString["Topic"] == null)
            {
                txt_Topic.Text = "";
            }
            else
            {
                txt_Topic.Text = Request.QueryString["Topic"];
            }
            if (_iQuestionID != -1)
            {
                txt_Question.Text = _question.Question;
                cb_MultiSelect.Checked = _question.MultiSelect;
                txt_Sequence.Text = _question.Sequence.ToString();
            }

            if (_dtOption != null)
            {
                gv_Options.DataSource = _dtOption;
                gv_Options.DataBind();
            }
            if (_topic.QuestionList != null)
            {
                DataTable questionTable=new DataTable();
                InitQuestionTable(questionTable);
                questionTable = DataTable2Object.ConvertToDataTableFromList(_topic.QuestionList);
                this.ddlAllQuestions.DataSource = questionTable;
                this.ddlAllQuestions.DataTextField = questionTable.Columns[2].ColumnName;
                this.ddlAllQuestions.DataValueField = "I_ID";
                this.ddlAllQuestions.DataBind();
            }
        }
        private void InitOptionTable()
        {
            if (_dtOption == null)
            {
                _dtOption = new DataTable();
                _dtOption.Columns.Add("I_ID");
                _dtOption.Columns.Add("I_QUESTION_ID");
                _dtOption.Columns.Add("S_OPTION");
                _dtOption.Columns.Add("I_NEXTQUESTION");
                _dtOption.Columns.Add("B_DELETED");
                _dtOption.Columns.Add("S_LAST_UPDATER");
                _dtOption.Columns.Add("D_LAST_UPDATE_DATE");
            }
        }
        private void InitQuestionTable(DataTable _dtQuestion)
        {
            //if (_dtQuestion == null)
            //{
            //    _dtQuestion = new DataTable();
                _dtQuestion.Columns.Add("I_ID");
                _dtQuestion.Columns.Add("I_TOPIC_ID");
                _dtQuestion.Columns.Add("S_QUESTION");
                _dtQuestion.Columns.Add("I_SEQUENCE");
                _dtQuestion.Columns.Add("B_MULTI_SELECT");
                _dtQuestion.Columns.Add("S_LAST_UPDATER");
                _dtQuestion.Columns.Add("D_LAST_UPDATE_DATE");
                _dtQuestion.Columns.Add("S_CREATOR");
                _dtQuestion.Columns.Add("D_CREATEDATE");
            //}
        }
    }
}